"""
题目：给定单链表头节点和目标值，统计链表中值等于目标值的节点出现的次数，返回次数。
"""


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def count_target_occurrences(head, target):
    """统计链表中值为target的节点出现次数"""
    count = 0
    current = head
    # 遍历链表，遇到目标值则计数器+1
    while current:
        if current.val == target:
            count += 1
        current = current.next
    return count


def create_linked_list(arr):
    if not arr:
        return None
    head = ListNode(arr[0])
    current = head
    for val in arr[1:]:
        current.next = ListNode(val)
        current = current.next
    return head


def traverse_linked_list(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result


# 测试
if __name__ == "__main__":
    # 测试1：目标值多次出现
    head1 = create_linked_list([1, 2, 2, 3, 2])
    print(count_target_occurrences(head1, 2))  # 输出: 3

    # 测试2：目标值出现一次
    head2 = create_linked_list([1, 2, 3])
    print(count_target_occurrences(head2, 2))  # 输出: 1

    # 测试3：目标值不出现
    head3 = create_linked_list([1, 2, 3])
    print(count_target_occurrences(head3, 4))  # 输出: 0

    # 测试4：空链表
    head4 = create_linked_list([])
    print(count_target_occurrences(head4, 0))  # 输出: 0